//
//  HTOAuthController.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/19.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit
import SVProgressHUD
//import SVProgressHUD
//定义appkey
let WB_APP_KEY = "3449423477"
// 回调页一定要与在开放平台上面设置的一模一样
let WB_REDIRECT_URI = "http://www.baidu.com/"

let WB_APP_SECRET = "380200e2ded01753a3c071c207d99aaf"

class HTOAuthController: UIViewController {
    

    //先定义一个webView
    private lazy var webView : UIWebView = {
    
        let webView = UIWebView()
        
        webView.delegate = self
        
        return webView
    }()
    
    
    
    override func loadView() {
        view = webView
        
        //让webview加载登陆页面
        let  urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        //print(request)
        
        webView.loadRequest(request)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        
    }
    
    
    func setupUI(){
    
        self.view.backgroundColor = UIColor.whiteColor()
        
        title = "登陆"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }

   @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFill(){
        
        let jsString = //"document.getElementById('userId').value='wwh1062078349@sina.cn';document.getElementById('passwd').value='wwh@527+nchu'"
        "document.getElementById('userId').value='gouqiaozhao60@163.com';document.getElementById('passwd').value='aaa333'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    

}

extension HTOAuthController :UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else{
        
            return false
        }
        
        //判断 url 的地址 是否可以回调
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI){
        
            if let q = url.query where q.containsString("code="){
            
                let code = q.substringFromIndex("code=".endIndex)
                
                print(code)
                
                HTViewModel.sharedViewModel.loadAccessToken(code,finish: {(isSuccess) -> () in
                
                    if isSuccess {
                        
//                        let alertViewController = UIAlertController(title: "登陆成功", message: "Message", preferredStyle: .Alert)
//                        
//                        let  okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
//                        
//                        alertViewController.addAction(okAction)
//                        print("登陆成功")
                        
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
                        appDelegate?.window?.rootViewController = HTWelComeController()
                        })
                    }else{
                    
                        let alertViewController = UIAlertController(title: "登陆失败", message: ",essage", preferredStyle: .Alert)
                        
                        let cancelAction = UIAlertAction(title: "cancel", style: .Cancel, handler: nil)
                        alertViewController.addAction(cancelAction)
                        
                        print("登陆失败")
                    }
                
                })
            }
//            return false
        }
        return true
        
    }
    
//    private func loadAccessToken(code:String){
//        
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        
//        let params = [
//            "client_id": WB_APP_KEY,
//            "client_secret": WB_APP_SECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WB_REDIRECT_URI
//        ]
//        
//        NetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
//            
//            
//            if error != nil{
//            
//                print("error")
//                return
//            }
//            print(responseObject)
//            guard let dict = responseObject as? [String : AnyObject] else{
//            
//                
//                
//                return
//            }
//            
//            let account = HTAccountModel(dict : dict)
//            
//            print(account)
//            
//            self.loadUserinfo(account)
//        }
//    }
//    
//    
//    //获取个人信息
//    private func loadUserinfo(account : HTAccountModel){
//        
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        
//        let params = [
//            
//            "access_token": account.access_token ?? "",
//            "uid": account.uid ?? ""
//        
//        ]
//        
//        NetworkTools.sharedTools.request(.Get, urlString: urlString, parameters: params) { (responseObject, error) -> () in
//            
//            if error != nil{
//            
//                print(error)
//                
//                return
//            }
//            
//            print(responseObject)
//            
//            guard let dict = responseObject as? [String : AnyObject] else{
//            
//                
//                print("格式不对")
//                return
//            }
//            
//           account.name = dict["name"] as? String
//            account.avatar_large = dict["avatar_large"] as? String
//            
//            print(account)
//            
//        }
//        
//    }
//    
//    
//    
//    //保存个人信息
//    private func saveAccount(account : HTAccountModel){
//    
//        let  path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
//        
//        print(path)
//        
//        NSKeyedArchiver.archiveRootObject(account, toFile: path)
//        
//    
//    }
//    
//    //去沙盒中读取
//    private func accountInsanBox() -> HTAccountModel?{
//    
//        let  path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
//        
//        let  result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? HTAccountModel
//        
//        return result
//    }
    
//    func webViewDidStartLoad(webView: UIWebView) {
//        
//        SVProgressHUD.show()
//    }
//    
//    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
//    }

    
}
